package com.cn.boot.student.service.rbac.impl;

import com.cn.boot.student.service.common.impl.RedisServiceImpl;
import com.cn.boot.student.util.CommonResult;
import com.cn.boot.student.entity.RoleEntity;
import com.cn.boot.student.mapper.RoleMapper;
import com.cn.boot.student.service.rbac.IRoleService;
import com.cn.boot.student.util.Tool;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * 角色服务逻辑层
 */
@Service
//开启缓存
@CacheConfig(cacheNames = "role")
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RedisServiceImpl redisService;

    /**
     * 查询所有，条件查询，分页
     */
    @Override
    public CommonResult findAll(RoleEntity roleEntity) {
        //得到数据总数
        Integer count = roleMapper.getCount(roleEntity);
        //分页
        PageHelper.startPage(Tool.toPageNum(roleEntity.getPageNum()),Tool.toPageSize(roleEntity.getPageSize()));
        List<RoleEntity> list = roleMapper.findAll(roleEntity);
        //得到分页信息
        PageInfo<RoleEntity> pageInfo = new PageInfo<>(list);
        HashMap<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("pageInfo",pageInfo);
        return CommonResult.success(map);
    }

    /**
     * 添加数据
     *
     * @param roleEntity
     */
    @Override
    public CommonResult add(RoleEntity roleEntity) {
//        RoleEntity roleEntity = roleMapper.findRoleName(r
//                oleEntity.getName());
        Integer result = roleMapper.add(roleEntity);
        return CommonResult.success(result);
    }

    /**
     * 更新数据
     *
     * @param roleEntity
     */
    @Override
    public CommonResult update(RoleEntity roleEntity) {
        Integer result = roleMapper.update(roleEntity);
        return CommonResult.success(result);
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Override
//    @CacheEvict(key = "'findAll[]'")
    public CommonResult del(Integer id) {
        Integer result = roleMapper.del(id);
        return CommonResult.success(result);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
//    @CacheEvict(key = "'findAll[]'")
    public CommonResult dels(List<Integer> ids) {
        ids.stream().forEach(roleMapper::del);
        //返回删除条数
        return CommonResult.success(ids.size());
    }

    /**
     * 根据id查询角色
     *
     * @param id
     */
    @Override
//    @Cacheable(keyGenerator = "keyGenerator")
    public CommonResult findById(Integer id) {
        RoleEntity roleEntity = roleMapper.findById(id);
        return CommonResult.success(roleEntity);
    }
}
